package javax.xianfeng.system.filter;

import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import lombok.extern.slf4j.Slf4j;

/**
 * 全局过滤器
 * @since 2020/01/03 20:35:16
 */
@Slf4j
@WebFilter(urlPatterns = "/*", filterName = "GlobalFilter")
public class GlobalFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		// 计时开始
		Instant startTime = Instant.now();

		// 打印请求服务信息
		String requestURI = request.getRequestURI();
		log.info("url = {}", requestURI);

		try {
			// 执行请求服务
			filterChain.doFilter(request, response);
		} finally {
			// 打印服务调用耗时
			Instant endTime = Instant.now();
			long millis = ChronoUnit.MILLIS.between(startTime, endTime);
			log.info("url = {}, time =  {} ms", requestURI, millis);
		}
	}

}
